import React, { useState, useRef, useEffect } from 'react';

const LazyImage = ({ src, ratio, placeholder, alt, style }) => {
    const initplaceholder =
        ratio == 'horizontal'
            ? 'https://img.alicdn.com/imgextra/i4/O1CN01wfWEiJ1ZklZG5L9Ly_!!6000000003233-2-tps-780-332.png'
            : 'https://img.alicdn.com/imgextra/i1/O1CN01K31lOD1dIbgCVZiHO_!!6000000003713-2-tps-440-780.png';
    const [imgSrc, setImgSrc] = useState(initplaceholder || placeholder);
    const imgRef = useRef();

    useEffect(() => {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    setImgSrc(src);
                    observer.unobserve(entry.target);
                }
            });
        });

        if (imgRef.current) {
            observer.observe(imgRef.current);
        }

        return () => observer.disconnect();
    }, [src]);

    return (
        <img
            ref={imgRef}
            src={imgSrc}
            alt={alt}
            className="lazy-render-img"
            style={{
                ...style,
                transition: 'opacity 0.3s ease',
                opacity: imgSrc === src ? 1 : 0.6,
            }}
            onLoad={(e) => {
                e.target.style.opacity = 1;
            }}
        />
    );
};

export default LazyImage;
